package com.example.demo.service;

import com.example.demo.constant.RoleConstant;
import com.example.demo.dao.UserDao;
import com.example.demo.entity.UserEntity;
import com.example.demo.service.interf.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * Created by hongzhenyue on 18/3/6.
 */
@Service
public class BaseUserService implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public int insert(UserEntity userEntity) {
        if (exist(userEntity.getUsername()))
            return 0;
        encryptPassword(userEntity);
        userEntity.setRoles(RoleConstant.ROLE_USER);
        return userDao.insert(userEntity);
    }

    @Override
    public UserEntity getByUsername(String username) {
        return userDao.selectByUsername(username);
    }

    /**
     * 判断用户是否存在
     *
     * @param username 账号
     * @return 密码
     */
    private boolean exist(String username) {
        UserEntity userEntity = userDao.selectByUsername(username);
        return (userEntity != null);
    }

    /**
     * 加密密码
     */
    private void encryptPassword(UserEntity userEntity) {
        String password = userEntity.getPassword();
        password = new BCryptPasswordEncoder().encode(password);
        userEntity.setPassword(password);
    }
}
